﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RooHui.Infrastructure.Component.WorkPool;
using RooHui.Infrastructure.Component.WorkPool.WorkHandle.ShortMessage;
using RooHui.Infrastructure.Configuration;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Infrastructure.Entities.Enum;
using RooHui.Tool;

namespace RooHui.OA.Biz
{
    public class SupportBiz
    {
        #region 手机验证码
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="username"></param>
        /// <param name="mobile"></param>
        /// <returns>返回正确的验证码</returns>
        public static string SendShortMessageCode(string username, string mobile, CheckCodeType checkCodeType)
        {
            try
            {
                var code = new CheckCodeStream().Find(c => c.UserName == username && c.Mobile == mobile
                 && c.Type == (int)checkCodeType);
                var newcode = new Random(DateTime.Now.Millisecond).Next(100000, 999999);
                if (code == null)
                {
                    //第一次获取此类型验证码
                    //添加此类型验证码
                    var checkCodeStream = new CheckCodeStream()
                    {
                        Code = newcode.ToString(),
                        ExpireDate = DateTime.Now.Add(new TimeSpan(0, 5, 0)),
                        RecordDate = DateTime.Now,
                        Type = checkCodeType,
                        UserName = username,
                        Mobile = mobile
                    }.PostAdd();
                }
                else
                {
                    code.Code = newcode.ToString();
                    code.ExpireDate = DateTime.Now.Add(new TimeSpan(0, 5, 0));
                    code.RecordDate = DateTime.Now;
                    code.PostModify();
                    //覆盖之前验证码
                }
                WorkPool.Append<NormalMessage>(WorkType.shortmessage_for_normal,
                            new NormalMessage()
                            {
                                Message = String.Format("您正在登录{0}的后台管理系统，短信验证码为：{1}，请勿泄漏此验证码，【{0}】",
                                    SiteSettings.SiteName, newcode),
                                Recipient = mobile
                            });
                return newcode.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return "";
        }

        public static bool CheckShortMessageCode(string username, string mobile, string mobileCode, CheckCodeType checkCodeType)
        {
            var code = new CheckCodeStream().Find(c => c.UserName == username && c.Mobile == mobile
             && c.Type == (int)checkCodeType);
            if (code == null || code.ExpireDate < DateTime.Now || code.Code != mobileCode)
            {
                return false;
            }
            return true;
        }
        #endregion
        #region 身份证验证
        public static bool CheckIDCardNo(string idCardNo, ref Gender gender)
        {
            try
            {
                if (idCardNo.Length != 18)//长度验证
                {
                    return false;
                }
                long n = 0;
                if (long.TryParse(idCardNo.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(idCardNo.Replace('x', '0').Replace('X', '0'), out n) == false)//数字验证
                {
                    return false;
                }
                string birthDay = idCardNo.Substring(6, 8).Insert(6, "-").Insert(4, "-");
                DateTime time = new DateTime();
                if (DateTime.TryParse(birthDay, out time) == false)//生日验证(YYYYMMDD)
                {
                    return false;
                }
                //做地址验证
                var county = new County().Find(idCardNo.Remove(6));
                if (county == null)
                {
                    return false;
                }
                string[] arrVarifyCode = ("1,0,X,9,8,7,6,5,4,3,2").Split(',');//校验位(R)
                //S = Sum(Ai * Wi), i = 0, ... , 16 其中 Ai 表示第 i 位置上的身份证号码数字值，Wi 表示第 i 位置上的加权因子，其各位对应 的值依次为： 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 
                string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');//i位置上的加权因子
                char[] Ai = idCardNo.Remove(17).ToCharArray();
                int sum = 0;
                for (int i = 0; i < 17; i++)
                {
                    sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());//17 位数字本体码加权求和
                }
                int y = -1;
                Math.DivRem(sum, 11, out y);//Y = mod(S, 11)
                //Y 值： 0 1 2 3 4 5 6 7 8 9 10 
                //校验码： 1 0 X 9 8 7 6 5 4 3 2
                if (arrVarifyCode[y] != idCardNo.Substring(17, 1).ToUpper())//取得Y值对应的校验位和身份证校验位比较
                {
                    return false;//校验码验证
                }
                //获取性别
                int seqnum = Convert.ToInt32(idCardNo.Substring(14, 3));
                if (seqnum % 2 == 1)
                {
                    gender = Gender.Male;
                }
                else
                {
                    gender = Gender.Female;
                }
                return true;//符合18位身份证号标准
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.Web, ex);
            }
            return false;
        }
        #endregion
        #region 获取随机号码
        public static string RandomCode(string prvoinceCode)
        {
            var newcode = new Random(DateTime.Now.Millisecond).Next(1000, 9999);
            var agentInfo = new AgentInfo().Find(c => c.AgentCode == (prvoinceCode+newcode.ToString()));
            if (agentInfo != null)
            {
                RandomCode(prvoinceCode);
            }
            return prvoinceCode + newcode.ToString();
        }
         
        #endregion
    }
}
